from django.db import models
from django.contrib.auth.models import User
from django.core.files.storage import default_storage
from django.core.exceptions import ValidationError
from django.conf import settings

class TravelRecord(models.Model):
    """旅游记录模型"""
    title = models.CharField(max_length=200, verbose_name="标题")
    description = models.TextField(verbose_name="描述", blank=True)
    location = models.CharField(max_length=200, verbose_name="位置", blank=True, default="")
    latitude = models.FloatField(verbose_name="纬度", null=True, blank=True)
    longitude = models.FloatField(verbose_name="经度", null=True, blank=True)
    start_date = models.DateField(verbose_name="开始日期")
    end_date = models.DateField(verbose_name="结束日期", null=True, blank=True)
    images = models.JSONField(verbose_name="图片列表", default=list, blank=True)
    main_image_index = models.IntegerField(
        verbose_name="主图索引",
        null=True, 
        blank=True,
        help_text="从图片列表中选择的主图索引（从0开始），为空则使用第一张图片"
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="user")

    class Meta:
        verbose_name = "旅游记录"
        verbose_name_plural = "旅游记录"
        ordering = ['-created_at']

    def __str__(self):
        return self.title

    def clean(self):
        """自定义验证：确保结束日期不早于开始日期"""
        super().clean()
        
        if self.end_date and self.start_date:
            if self.end_date < self.start_date:
                raise ValidationError({
                    'end_date': '结束日期不能早于开始日期'
                })

    def delete(self, *args, **kwargs):
        """删除旅游记录时同时删除关联的图片文件"""
        # 删除所有关联的图片文件
        for image_url in self.images:
            try:
                if image_url and isinstance(image_url, str):
                    # 处理本地文件路径
                    if image_url.startswith(settings.MEDIA_URL):
                        file_path = image_url.replace(settings.MEDIA_URL, '')
                        if default_storage.exists(file_path):
                            default_storage.delete(file_path)
                    # 处理完整的URL（包含https://）
                    elif image_url.startswith('https://'):
                        # 提取文件路径
                        file_path = image_url.split('/media/')[1]
                        if default_storage.exists(file_path):
                            default_storage.delete(file_path)
            except Exception as e:
                # 记录错误但继续处理，避免影响其他操作
                print(f"删除图片文件失败: {image_url}, 错误: {str(e)}")
        
        # 调用父类的delete方法
        super().delete(*args, **kwargs)

class Comment(models.Model):
    """评论模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    travel_record = models.ForeignKey(TravelRecord, on_delete=models.CASCADE, related_name='comments', verbose_name="旅游记录")
    content = models.TextField(verbose_name="评论内容")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "评论"
        verbose_name_plural = "评论"
        ordering = ['created_at']

    def __str__(self):
        return f"{self.user.username} - {self.travel_record.title}"

class Like(models.Model):
    """点赞模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    travel_record = models.ForeignKey(TravelRecord, on_delete=models.CASCADE, related_name='likes', verbose_name="旅游记录")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "点赞"
        verbose_name_plural = "点赞"
        unique_together = ['user', 'travel_record']

    def __str__(self):
        return f"{self.user.username} 点赞了 {self.travel_record.title}"
